package com.android.versiondownloadlibrary;

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.annotation.Nullable;

import java.lang.ref.WeakReference;

/**
 * Created by $Liudan on 2018/5/16 0016.
 */
public class VersionService extends Service {
    private String url;
    private int update_mode;
    private MyHandler myHandler;
    private UpdateUi updateUi;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        myHandler = new MyHandler(this);
        updateUi = UpdateUiFactory.getUpdateUI(this, update_mode);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        url = intent.getStringExtra("url");
        update_mode = intent.getIntExtra("update_mode", UpdateUi.update_normal);
        updateUi.createUi(this);
        VersionMgr.getInstance().httpRequest(this, url, update_mode, myHandler, updateUi);
        return super.onStartCommand(intent, flags, startId);
    }

    static class MyHandler extends Handler {
        private final WeakReference<VersionService> weakReference;

        public MyHandler(VersionService activity) {
            weakReference = new WeakReference<VersionService>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            VersionService weakParent = weakReference.get();
            if (weakParent == null) return;
            switch (msg.what) {
                case 1:
                    weakParent.updateUi.updateUI(msg.arg1,msg.arg2);
                    break;
            }
        }
    }
}
